import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;

public class LoginController extends Controller
{
	private static final long	serialVersionUID	= 2427806439351478096L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		super.doGet(request, response);
	}

	public void index(HttpServletRequest request, HttpServletResponse response) throws InstantiationException, IllegalAccessException, UnsupportedEncodingException, IOException
	{
		String html = getViewHtml("login", "login");
		html = html.replaceAll("\\{path\\}", StaticMethods.PATH);
		renderView(html, response);
	}

	public void authenticate(HttpServletRequest request, HttpServletResponse response) throws InstantiationException, IllegalAccessException, ServletException, IOException, NoSuchAlgorithmException
	{
		String username = request.getParameter("username").trim();
		String password = StaticMethods.MD5(request.getParameter("password").trim());
		User user = User.getUser(getSession(), username, password);
		if ( user != null )
		{
			HttpSession httpSession = request.getSession(true);
			httpSession.setAttribute("user", user.getId());
			httpSession.setAttribute("role", user.getRole());
			response.sendRedirect("/miat/main");
		}
	}

	public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession httpSession = request.getSession();
		httpSession.removeAttribute("user");
		httpSession.removeAttribute("role");
		response.sendRedirect("/miat/login");
	}
}
